<template>
  <div>
    <van-cell
    v-for="(item, index) in suggestion"
    :key="index"
    icon="search">
      <div @click="$emit('search', item)" slot="title" v-html="highlight(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
// import { debounce } from 'lodash'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestion: [],
      setTimeId: 0
    }
  },

  created () {

  },

  watch: {
    searchText: {
      // handler: 监听数据发生变化，就会触发该钩子函数
      handler () {
        clearTimeout(this.setTimeId)
        this.setTimeId = setTimeout(() => {
          this.loadSuggestion()
        }, 700)
      },
      // handler: debounce(function () {
      //   this.loadSuggestion()
      // }, 1000),
      immediate: true
    }
  },

  methods: {
    // 加载联系建议
    async loadSuggestion () {
      try {
        const { data: res } = await getSearchSuggestion(this.searchText)
        this.suggestion = res.data.options
      } catch (err) {
        this.$toast.fail('获取数据失败')
      }
    },
    // 处理搜索建议每一项的高亮
    highlight (text) {
      // text: 要处理的每一项文本
      const replaceStr = `<span style="color: #3296fa">${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      const newText = text.replace(reg, replaceStr)
      return newText
    }
  }
}
</script>

<style scoped lang='less'>

</style>
